<script lang="ts" setup>
import { useSystemStore } from '~/stores/system'
import { keys, isEmpty } from 'lodash'

interface Field {
  label: string
  prop: string
}

interface IProps {
  visible: boolean
  columns: Field[]
  data: Record<string, any>
}

const { t } = useI18n()
const syStore = useSystemStore()

const props = defineProps<IProps>()
const emit = defineEmits(['update:visible', 'commit'])

const display = computed({
  get: () => props.visible,
  set: (value: boolean) => {
    emit('update:visible', value)
    if (!value) {
      resetFields() 
    }
  }
})

const state = reactive<any>({})

watch(() => props.data, (val) => {
  keys(val).forEach((k: string) => {
    state[k] = val[k]
  })
})

const resetFields = () => {
  keys(props.data).forEach((k: string) => {
    state[k] = undefined
  })
}

const handleCommit = () => {
  emit('commit', toRaw(state))
  emit('update:visible', false)
  resetFields()
}

const labelWidth = computed(() => {
  const maxLabelLength = Math.max(...props.columns.map(col => col.label.length))
  return maxLabelLength * 13
})

const columns = computed(() => {
  const exclude = syStore.excludeKeys
  return props.columns.filter((k) => !exclude.includes(k.prop))
})

const title = computed(() => {
  const hasRecord = !isEmpty(props.data)
  return hasRecord ? t('edit_record') : t('create_record')
})

</script>

<template>
  <Dialog 
    v-model:visible="display" 
    :title="title" 
    :width="500"
    @commit="handleCommit">
    <el-form :model="state" :label-width="labelWidth" @submit.native.prevent>
      <el-form-item
        v-for="(column, index) in columns"
        :key="index"
        :label="column.label"
        :prop="column.prop">
        <el-input   
          @keyup.enter="handleCommit" 
          v-model="state[column.prop]" 
          :placeholder="$t('enter_input')" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>
